package psn.hui.sys.controller;

import java.io.IOException;
import java.util.Date;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mysql.cj.log.Log;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import psn.hui.sys.constant.SysConstant;
import psn.hui.sys.domain.LogInfo;
import psn.hui.sys.domain.User;
import psn.hui.sys.service.LogInfoService;
import psn.hui.sys.service.UserService;
import psn.hui.sys.utils.WebUtils;
import psn.hui.sys.vo.UserVo;

/**
 * 	用户登录控制器
 * @author hui
 *
 */
@Controller
@RequestMapping("login")
public class LoginController {
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private  LogInfoService LogInfoService;
	
	/**
	 *	跳转到登录页面
	 */
	@RequestMapping("toLogin")
	public String toLogin() {
		return "system/main/login";
	}
	/**
	 * 	登录
	 */
	@RequestMapping("login")
	public String login(UserVo userVo, Model model) {
		HttpSession session = WebUtils.getHttpSession();
		String captchaCode = (String)session.getAttribute("captchaCode");
		if(null == captchaCode || !captchaCode.equals(userVo.getCaptchaCode())) {
			model.addAttribute("error",SysConstant.USER_LOGIN_CODEERROR_MSG);
			return "system/main/login";
		}
		User user = userService.login(userVo);
		if(null != user) {
			//放入session
			WebUtils.getHttpSession().setAttribute("user", user);
			//记录登录日志，想sys_log_login里插入数据
			LogInfo logInfo = new LogInfo();
			logInfo.setLoginname(user.getRealname()+":"+user.getLoginname());
			logInfo.setLoginip(WebUtils.getHttpServletRequest().getRemoteAddr());
			logInfo.setLogintime(new Date());
			LogInfoService.addLogInfo(logInfo);
			
			return "system/main/index";
		}else {
			model.addAttribute("error",SysConstant.USER_LOGIN_ERROR_MSG);
			return "system/main/login";
		}
	}
	
	/**
	 * 	得到登录验证码
	 * 
	 */
	@RequestMapping("getCaptchaImage")
	public void getCaptcha(HttpServletResponse response,HttpSession session) {
		try {
			LineCaptcha captcha = CaptchaUtil.createLineCaptcha(116, 36,4,20);
			session.setAttribute("captchaCode", captcha.getCode());
			ImageIO.write(captcha.getImage(), "PNG", response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
